package top.coolrainly.module.pb.service.organization;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import top.coolrainly.module.pb.controller.admin.organization.vo.*;
import top.coolrainly.module.pb.dal.dataobject.organization.OrganizationDO;
import top.coolrainly.framework.common.pojo.PageResult;
import top.coolrainly.framework.common.pojo.PageParam;
import top.coolrainly.framework.common.util.object.BeanUtils;

import top.coolrainly.module.pb.dal.mysql.organization.OrganizationMapper;

import static top.coolrainly.framework.common.exception.util.ServiceExceptionUtil.exception;
import static top.coolrainly.module.pb.enums.ErrorCodeConstants.*;

/**
 * 党组织信息 Service 实现类
 *
 * @author CoolRainLy
 */
@Service
@Validated
public class OrganizationServiceImpl implements OrganizationService {

    @Resource
    private OrganizationMapper organizationMapper;

    @Override
    public Long createOrganization(OrganizationSaveReqVO createReqVO) {
        // 插入
        OrganizationDO organization = BeanUtils.toBean(createReqVO, OrganizationDO.class);
        organizationMapper.insert(organization);
        // 返回
        return organization.getId();
    }

    @Override
    public void updateOrganization(OrganizationSaveReqVO updateReqVO) {
        // 校验存在
        validateOrganizationExists(updateReqVO.getId());
        // 校验上级组织
        validityOrganizationParent(updateReqVO.getId(), updateReqVO.getParentId());
        // 更新
        OrganizationDO updateObj = BeanUtils.toBean(updateReqVO, OrganizationDO.class);
        organizationMapper.updateById(updateObj);
    }

    @Override
    public void deleteOrganization(Long id) {
        // 校验存在
        validateOrganizationExists(id);
        // 删除
        organizationMapper.deleteById(id);
    }

    private void validateOrganizationExists(Long id) {
        if (organizationMapper.selectById(id) == null) {
            throw exception(ORGANIZATION_NOT_EXISTS);
        }
    }

    private void validityOrganizationParent(Long id, Long parentId) {
        if (parentId == null) {
            return;
        }
        if(Objects.equals(id, parentId)) {
            throw exception(ORGANIZATION_NOT_ALLOW_ONESELF);
        }
    }

    @Override
    public OrganizationDO getOrganization(Long id) {
        return organizationMapper.selectById(id);
    }

    @Override
    public PageResult<OrganizationDO> getOrganizationPage(OrganizationPageReqVO pageReqVO) {
        return organizationMapper.selectPage(pageReqVO);
    }

    @Override
    public List<OrganizationDO> getOrganizationList() {
        return organizationMapper.selectList();
    }

}